<template>
  <a-form ref="formRef" :model="formData" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
    <a-row>
      <a-col :span="24">
        <a-form-item label="指令名称" name="zlmc">
          <a-input v-model:value="formData.zlmc" :placeholder="rules.zlmc.message" />
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item label="指令类型" name="zllx">
          <a-select
            v-model:value="formData.zllx"
            :options="zllxList"
            :placeholder="rules.zllx.message"
            :get-popup-container="getContainer"
          />
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item label="指令级别" name="zljb">
          <a-select
            v-model:value="formData.zljb"
            :options="zljbList"
            :placeholder="rules.zljb.message"
            :getPopupContainer="getContainer"
          />
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item label="选择签收单位" name="dw">
          <a-tree-select
            :disabled="true"
            v-model:value="formData.dw"
            show-search
            multiple
            allowClear
            label-in-value
            treeNodeFilterProp="label"
            placeholder="选择签收单位"
            :tree-data="unitTreeList"
            :tree-checkable="true"
            :getPopupContainer="getContainer"
            :height="300"
          />
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item label="指令内容" name="zlnr">
          <a-textarea v-model:value="formData.zlnr" :auto-size="{ minRows: 4 }" placeholder="请输入备注" />
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item label="推送行业主管部门">
          <!-- 自建房详情里面有这个值，无法进行选择修改 -->
          <a-tree-select
            :disabled="data.details.industry_regulatory_authorities ? true : false"
            v-model:value="formData.industry_regulatory_authorities"
            label-in-value
            show-search
            allowClear
            treeNodeFilterProp="label"
            placeholder="选择推送行业主管部门"
            :tree-data="wbUnitList"
            :field-names="{
              children: 'nodes',
              label: 'text',
              value: 'code',
            }"
            :getPopupContainer="getContainer"
            :height="300"
            @change="tshyzgbmChange"
          />
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item label="推送内容" name="tsnr">
          <a-textarea v-model:value="formData.tsnr" :auto-size="{ minRows: 4 }" placeholder="请输入推送内容" />
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>

<script>
import { instructionUpdate, instructionAdd, sendMsgZjfZl, sendMsgZjfZgbm } from '@gis/lib/api';
import { handleCommonRes, handleFormResult } from '@gis/lib/utils/resolver.js';
import { getEnumList } from '@gis/lib/enums';
import get from 'lodash-es/get.js';
import { instructionUnit, getUnitTree } from '@gis/lib/api';
import { useTreeDataStore } from '@gis/lib/pinia/treeData.js';
import { useUserInfoStore } from '@gis/lib/pinia/userInfo.js';

export default {
  name: 'AddEdit',
  props: {
    data: Object, //area_code、address、security_investigation_number、details
  },
  data() {
    return {
      wbUnitList: [], //委办单位
      unitTreeList: [],
      rules: {
        zlmc: { required: true, message: '请填写指令名称' },
        zllx: { required: true, message: '请选择指令类型' },
        zljb: { required: true, message: '请选择指令级别' },
        dw: { required: true, message: '请选择签收单位' },
        zlnr: { required: true, message: '请填写指令内容' },
      },
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      formData: {
        zlmc: '关于自建房安全隐患排查',
        zllx: '签收',
        zljb: '紧急',
      },
      zljbList: getEnumList('zljb', null, 'useString'),
      zllxList: getEnumList('zllx', null, 'useString'),
    };
  },
  async mounted() {
    await this.getUnitList();
    await this.getWbUnitList();
    this.formData = Object.assign({}, this.formData, {
      industry_regulatory_authorities: {
        label: get(this.data, 'details.industryRegulatoryAuthoritiesVal', ''),
        value: get(this.data, 'details.industry_regulatory_authorities', ''),
      },
      zlnr: `${get(this.formData.dw, '[0].unit_name', '')}，你单位位于${this.data.address}的自建房（编号：${
        this.data.security_investigation_number
      }），初判存在一定安全隐患，尚未完成整治销号，根据《成都市自建房安全管理办法》，请切实履行监管职责，采取整治措施，完成销号。`,
      tsnr: this.setTsnrValue(get(this.data, 'details.industryRegulatoryAuthoritiesVal', 'XXX')),
    });
  },
  methods: {
    setTsnrValue(val) {
      return `${val}，贵行业位于${this.data.address}的自建房（自建房排查编号：${this.data.security_investigation_number}），初判存在一定安全隐患，尚未完成整治销号，根据《成都市自建房安全管理办法》，请切实履行行业监管职责，督促属地政府和房屋使用安全责任人采取整治措施，完成销号。`;
    },
    tshyzgbmChange(item, label) {
      this.formData = Object.assign({}, this.formData, {
        tsnr: this.setTsnrValue(item.label),
      });
    },
    disabledTree(tree, cb) {
      let node = null;
      let list = [...tree];
      while ((node = list.shift())) {
        cb(node);
        node.nodes && list.push(...node.nodes);
      }
    },
    // 推送行业主管部门，该账号下所有委办单位
    async getWbUnitList() {
      const userInfoStore = useUserInfoStore();
      const data = await handleCommonRes(getUnitTree({ area_code: userInfoStore.area_code, is_contain_oneself: true }));
      this.disabledTree(data, (item) => {
        item.disabled = item.code.includes('@') ? false : true;
      });
      this.wbUnitList = data;
    },
    async getUnitList() {
      const data = await handleCommonRes(instructionUnit({ area_code: this.data.area_code }));
      this.unitTreeList = data.map((item) => Object.assign({}, item, { label: item.unit_name, value: item.unit_code }));
      this.formData.dw = get(this.unitTreeList, '[0]', undefined)
        ? [get(this.unitTreeList, '[0]', undefined)]
        : undefined;
    },
    getContainer() {
      return document.body;
    },
    async onOk() {
      const valid = await this.$refs.formRef.validate();
      if (!valid) return false;
      // 推送行业主管部门 有值
      // 推送内容 无值
      if (this.formData.industry_regulatory_authorities && !this.formData.tsnr) {
        this.$message.error(`请输入推送内容`);
        return false;
      }
      let id = get(this.data, 'id');
      let dw = get(this.formData, 'dw');
      let params = {
        id: id,
        zlmc: get(this.formData, 'zlmc'),
        zljb: get(this.formData, 'zljb'),
        zllx: get(this.formData, 'zllx'),
        zlnr: get(this.formData, 'zlnr'),
        qsdwmc: get(this.formData, 'dw[0].label'),
        qsdwbm: get(this.formData, 'dw[0].value'),
      };
      const api = id ? instructionUpdate : instructionAdd;
      console.log(params, this.formData, '提交值');
      // return false;
      return handleFormResult(await api(params), {
        onOk: async () => {
          const sendMsgParams = {
            unit_code: params.qsdwbm,
            unit_name: params.qsdwmc,
            address: this.data.address,
            number: this.data.security_investigation_number,
          };
          // 选择签收单位
          await sendMsgZjfZl(sendMsgParams);
          // 推送行业主管部门 - 有值
          if (
            this.formData.industry_regulatory_authorities &&
            get(this.formData.industry_regulatory_authorities, 'value', '')
          ) {
            await sendMsgZjfZgbm({
              unit_code: get(this.formData.industry_regulatory_authorities, 'value', ''),
              unit_name: get(this.formData.industry_regulatory_authorities, 'label', ''),
              address: this.data.address,
              number: this.data.security_investigation_number,
            });
          }
        },
      });
    },
  },
};
</script>

<style scoped></style>
